import { Link } from 'expo-router'
import {
  ImageSourcePropType,
  Platform,
  StyleSheet,
  Text,
  View,
} from 'react-native'
// import { Image } from 'expo-image'
import ImageViewer from '@/components/ImageViewer'
import Button from '@/components/Button'
import * as ImagePicker from 'expo-image-picker'
import { useState, useRef } from 'react'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import CircleButton from '@/components/CircleButton'
import IconButton from '@/components/IconButton'
import EmojiPicker from '@/components/EmojiPicker'
import EmojiList from '@/components/EmojiList'
import EmojiSticker from '@/components/EmojiSticker'
import * as MediaLibrary from 'expo-media-library'
import { captureRef } from 'react-native-view-shot'
import domtoimage from 'dom-to-image'

const PlaceholderImage = require('@/assets/images/background-image.png')

export default function Index() {
  const [selectImage, setSelectImage] = useState<string | undefined>(undefined)
  const [showAppOptions, setShowAppOptions] = useState<boolean>(false)
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false)
  const [pickedEmoji, setPickedEmoji] = useState<
    ImageSourcePropType | undefined
  >(undefined)
  const [status, requestPermission] = MediaLibrary.usePermissions()
  const imageRef = useRef<View>(null)
  if (status == null) {
    requestPermission()
  }
  const pickerImageAsync = async () => {
    let result = await ImagePicker.launchCameraAsync({
      mediaTypes: 'images',
      allowsEditing: true,
      quality: 1,
    })
    if (!result.canceled) {
      console.log(result)
      setSelectImage(result.assets[0].uri)
      setShowAppOptions(true)
    } else {
      alert('请选择图片')
    }
  }
  const onReset = () => {
    setShowAppOptions(false)
  }

  const onAddSticker = () => {
    setIsModalVisible(true)
  }

  const onModalClose = () => {
    setIsModalVisible(false)
  }

  const onSaveImageAsync = async () => {
    if (Platform.OS !== 'web') {
      try {
        const localUrl = await captureRef(imageRef, {
          height: 440,
          quality: 1,
        })
        console.log('localUrl', localUrl)
        await MediaLibrary.saveToLibraryAsync(localUrl)
        if (localUrl) {
          alert('保存成功！')
        }
      } catch (e) {
        console.log(e)
      }
    } else {
      try {
        const dataUrl = await domtoimage.toJpeg(imageRef.current as any, {
          quality: 0.95,
          width: 320,
          height: 440,
        })

        let link = document.createElement('a')
        link.download = 'sticker-smash.jpeg'
        link.href = dataUrl
        link.click()
      } catch (e) {
        console.log(e)
      }
    }
  }

  return (
    <GestureHandlerRootView style={styles.container}>
      <View style={styles.container}>
        {/* <Text style={styles.text}>首页</Text>
      <Link href='/tabs/about' style={styles.link}>
        导航到About页面
      </Link> */}
        <View style={styles.imageContainer}>
          {/* <Image source={PlaceholderImage} style={styles.image} /> */}
          <View ref={imageRef} collapsable={false}>
            <ImageViewer
              imgSource={PlaceholderImage}
              selectedImage={selectImage}
            />
            {pickedEmoji && (
              <EmojiSticker imageSize={40} stickerSource={pickedEmoji} />
            )}
          </View>
        </View>
        {showAppOptions ? (
          <View style={styles.optionsContainer}>
            <View style={styles.optionsRow}>
              <IconButton
                icon='refresh'
                label='重置'
                onPress={onReset}
              ></IconButton>
              <CircleButton onPress={onAddSticker}></CircleButton>
              <IconButton
                icon='save-alt'
                label='保存'
                onPress={onSaveImageAsync}
              ></IconButton>
            </View>
          </View>
        ) : (
          <View style={styles.footerContainer}>
            <Button
              label='选择图片'
              theme='primary'
              onPress={pickerImageAsync}
            ></Button>
            <Button
              label='使用这张图片'
              onPress={() => setShowAppOptions(true)}
            ></Button>
          </View>
        )}
        <EmojiPicker isVisible={isModalVisible} onClose={onModalClose}>
          <EmojiList onSelect={setPickedEmoji} onCloseModal={onModalClose} />
        </EmojiPicker>
      </View>
    </GestureHandlerRootView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#25292e',
  },
  text: {
    color: 'white',
  },
  link: {
    fontSize: 16,
    textDecorationLine: 'underline',
    color: 'white',
  },
  imageContainer: {
    flex: 1,
  },
  image: {
    width: 320,
    height: 440,
    borderRadius: 18,
  },
  footerContainer: {
    flex: 1 / 3,
    alignItems: 'center',
  },
  optionsContainer: {
    position: 'absolute',
    bottom: 80,
  },
  optionsRow: {
    alignItems: 'center',
    flexDirection: 'row',
  },
})
